<template>
  <div class="invoice-table-container">
    <SectionTitle :class="{'mobile':showMobilePage}" :style="`margin-bottom: ${showMobilePage?'66px':'22px'};`" title="发票信息" font-size="16px">
      <div v-if="!showMobilePage" style="margin-left: 10px;">
        <dataDisplay :data-list="[{ label: '含税金额', data: totalAmount, icon: incomeAmountIcon, width: '200px' }]"/>
      </div>
      <div style="flex:1"/>
      <div v-if="isEdit" :style="`${showMobilePage?'left: 0; top: 32px':''};`" class="options-btn-group">
        <PlainCreateBtn @click="onInvoiceAdd">添加</PlainCreateBtn>
        <ImportButton
          :import-api="'/admin/issue/invoice/info/import'"
          :show-icon="false"
          :is-icon-type="false"
          hide-confirm
          style="margin: 0 10px;"
          accept=".csv,.xls,.xlsx"
          type="uploadFile"
          @complateSetData="complateSetData"/>
        <el-button :disabled="deleteDisable" size="small" type="danger" plain class="option-btn" @click="onInvoiceDel">删除</el-button>
      </div>
    </SectionTitle>
    <dataDisplay v-if="showMobilePage" :data-list="[{ label: '含税金额', data: totalAmount, icon: incomeAmountIcon, width: '200px' }]" style="margin-bottom: 12px"/>
    <dynamicEditTable
      ref="dynamicEditTableRef"
      v-model="orders"
      :list-data="orders"
      :list-setting="listSetting"
      :is-edit="isEdit"
      :show-selection="isEdit"
      :show-serial="false"
      :show-add-btn="false"
      :show-delete-btn="false"
      :show-copy-btn="false"
      :if-fill="false"
      :default-params="defaultOrderItem"
      :order-private-id="orderPrivateId"
      class="invoice-table-content"
      @onSelectChange="onSelectChange"
      @orderPrivateIdChange="orderPrivateIdChange"
      @handleJump="toInvoiceDetail"
    />
  </div>
</template>

<script>
import { getUserList } from '@/api/user';
import SectionTitle from '@/components/Title';
import dynamicEditTable from '@/components/Common/dynamicEditTable';
import ImportButton from '@/components/ImportButton';
import { showModal } from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { mapState } from 'vuex';
export default {
  name: 'InvoiceInfo',
  components: {
    SectionTitle,
    ImportButton,
    dynamicEditTable, dataDisplay
  },
  props: {
    isEdit: {
      type: Boolean,
      default: true
    },
    showMobilePage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      incomeAmountIcon,
      defaultOrderItem: {
        customizeState: true,
        issuerId: '',
        userName: '',
        createTime: new Date().getTime()
      },
      orderPrivateId: 1,
      orders: [],
      deleteDisable: true,
      curSelectedRows: [],
      totalAmount: 0.00
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    listSetting() {
      return [{
        label: '发票号码',
        type: 'inputPureNumber',
        width: '150px',
        keyword: 'number',
        isRequired: true
      }, {
        label: '含税金额(元)',
        type: 'inputNumber',
        width: '150px',
        keyword: 'amount',
        maxnumber: 999999999,
        isRequired: true
      }, {
        label: '发票附件',
        type: 'multipleAttachment',
        width: '200px',
        keyword: 'attachment',
        importApi: 'admin/client/file/upload',
        uploadIcon: true
      }, {
        type: 'inputText',
        label: '发票状态',
        width: '200px',
        keyword: 'invoiceState',
        onlyRead: true,
        createText: '--',
        jump: true, // 是否需要跳转功能
        statusFilter: function(status) {
          return {
            0: '正数正常',
            1: '正数作废',
            2: '负数正常',
            3: '负数作废'
          }[status];
        },
        getColor(status) {
          return {
            0: '#31CC9C',
            1: '#999',
            2: '#31CC9C',
            3: '#999'
          }[status];
        }
      }, {
        label: '开票人',
        type: 'scrollSelect',
        width: '150px',
        keyword: this.isEdit ? 'issuerId' : 'userName',
        keyName: 'id',
        labelName: 'userName',
        loadmoreMethod: getUserList,
        extendParams: {
          type: 1
        }
      }, {
        label: '开票时间',
        type: 'datepicker',
        width: '180px',
        keyword: 'createTime',
        pickerType: 'datetime',
        pickerFormat: 'yyyy/MM/dd HH:mm',
        placeholder: '--',
        formatStr: 'YYYY/MM/DD HH:mm'
      }];
    }
  },
  watch: {
    orders: {
      handler(list) {
        const result = list.reduce((total, curr) => {
          const price = Number(curr.amount) ? Number(curr.amount) : 0;
          return price + total;
        }, 0);
        this.totalAmount = Number(result).toFixed(2);
      },
      immediate: true,
      deep: true
    },
    userInfo: {
      handler(data) {
        this.defaultOrderItem.issuerId = data.id;
        this.defaultOrderItem.userName = data.userName;
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    onInvoiceAdd() {
      this.defaultOrderItem.createTime = new Date().getTime();
      this.$refs['dynamicEditTableRef'].addValue();
    },
    // 提供给父组件来验证完整性
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs['dynamicEditTableRef'].validate().then(() => {
          const numbersMap = new Map();
          const dedupeResult = [];
          this.orders.forEach(item => {
            if (numbersMap.has(item.number)) {
              !dedupeResult.some(val => val === item.number) && dedupeResult.push(item.number);
            } else {
              numbersMap.set(item.number, true);
            }
          });
          if (dedupeResult.length) {
            this.$message.warning(`存在重复的发票号码：${dedupeResult.join('、')}`);
            reject();
          } else {
            resolve();
          }
        }).catch(() => {
          this.$message.warning('请检查信息是否填写完整');
          reject();
        });
      });
    },
    onInvoiceDel() {
      showModal('确认删除已选中的发票信息吗？', '', {}).then(_ => {
        let curRow;
        // eslint-disable-next-line no-cond-assign
        while (curRow = this.curSelectedRows.pop()) {
          for (let index = this.orders.length - 1; index >= 0; index--) {
            if (this.orders[index].orderPrivateId === curRow.orderPrivateId) {
              this.orders.splice(index, 1);
            }
          }
        }
      });
    },
    onSelectChange(list) {
      this.curSelectedRows = list;
      this.deleteDisable = !list.length;
    },
    orderPrivateIdChange(num) {
      if (!num) return;
      this.orderPrivateId = num;
    },
    complateSetData(data) {
      const importList = data && data.data || [];
      importList.forEach(item => {
        item.orderPrivateId = ++this.orderPrivateId;
      });
      this.orders.push(...importList);
    },
    setTableData(list) {
      list.forEach((item, index) => {
        item.orderPrivateId = index + 1;
        // status: 0: 开票执行中；1：开票已完成；2：作废中；3：已作废
        const disableStatus = hasRouteAuth('crm:invoiceIssue:invoiceChange') ? [2, 3] : [1, 2, 3];
        if (disableStatus.includes(item.status)) {
          item.disable = true;
        }
      });
      this.orderPrivateId = list.length + 1;
      this.orders = list;
    },
    toInvoiceDetail(row) {
      const url = this.$router.resolve({
        name: 'invoiceDetail',
        params: { id: row.id }
      });
      window.open(url.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.invoice-table-container {
  background: #fff;
  margin-top: 32px;
  & ::v-deep {
    .el-form-item {
      .el-select {
        width: 240px;
      }
      .el-input__inner {
        width: 240px;
      }
      .el-textarea__inner {
        height: 64px !important;
      }
    }
  }
  .invoice-table-content {
    ::v-deep .filterableSelect {
      width: 100%;
    }
  }
  .options-btn-group {
    display: flex;
    align-items: center;
    position: absolute;
    right: 0;;
    .option-btn {
      padding-left: 12px;
      padding-right: 12px;
    }
  }
}
.mobile {
  flex-wrap: wrap !important;
  margin-bottom: 56px;
}
</style>
